import logging
from typing import Any
from time import time
from fastapi import APIRouter, Depends, HTTPException, Request, Query
from fastapi_sqlalchemy import db
from datetime import datetime, timedelta
from app.helpers.exception_handler import CustomException
from app.helpers.login_manager import login_required, PermissionRequired
from app.helpers.paging import Page, PaginationParams, paginate
from app.schemas.sche_base import DataResponse
from app.schemas.sche_user import UserItemResponse, UserCreateRequest, UserUpdateMeRequest, UserUpdateRequest
from app.services.srv_user import UserService
from app.models.model_user import User
from app.schemas.sche_test import PublicKeyResponse, TestItemResponse, TestGithubRequest, TestGithubResponse, LoginResponse, LoginRequest 
from app.services.srv_public import PublicService

logger = logging.getLogger()
router = APIRouter()


@router.get("/")
def hello():
    return "hello world!!!"


@router.get("/test", response_model=DataResponse[TestItemResponse])
def test_router(request: Request):
    print(f"request: {request}")
    current_time = time()
    test_item = TestItemResponse(id=1, current_time=current_time, data=f"test_Router: receiver request {current_time}")
    return DataResponse().success_response(data=test_item)


@router.get("/get")
def get_info():
    return "get_info"


@router.get("/github", response_model = DataResponse[TestGithubResponse])
def query_githubUser(request: Request, params: TestGithubRequest = Depends()):
    # 使用 params.userName 获取用户名
    data = PublicService().requestGithub(params.name)
    return DataResponse().success_response(data = data)




@router.post("/v1/auth", response_model = DataResponse[LoginResponse])
def login(request : Request, form_data : LoginRequest):
    try:
        account, password = PublicService.decode_userInfo(form_data)
        print(account, password)
        token = PublicService.create_access_token({'sub': form_data.username})
        return DataResponse().success_response({'token_type' : 'login', 'access_token': token})
    except Exception as E:
        return CustomException(http_code=400, code='400', message=str(E))

@router.post("/key", response_model = DataResponse[PublicKeyResponse])
def get_publicKey():
    return DataResponse().success_response(PublicService.getPublicKey())